<?php
namespace app\api\controller\food\user;

use app\api\controller\food\Controller;
use app\api\model\Address as AddressModel;
use hema\wechat\Map;

/**
 * 收货地址管理
 */
class Address extends Controller
{
    private $user;

    /**
     * 构造方法
     */
    public function initialize()
    {
        parent::initialize();
        $this->user = $this->getUserDetail();   // 用户信息
    }

    /**
     * 收货地址列表
     */
    public function lists()
    {
        $model = new AddressModel;
        $list = $model->getList($this->user['user_id']);
        return $this->renderSuccess([
            'list' => $list,
            'default_id' => $this->user['address_id'],
        ]);
    }

    /**
     * 添加收货地址
     */
    public function add()
    {
        $model = new AddressModel;
        if ($model->add($this->request->post(),$this->user)) {
            return $this->renderMsg('添加成功');
        }
        $error = $model->getError() ?: '添加失败';
		return $this->renderError($error);
    }

    /**
     * 编辑收货地址
     */
    public function edit($id)
    {
        $detail = AddressModel::get($id);
        if (!$this->request->isPost()) {
            return $this->renderSuccess(compact('detail'));
        }
        if ($detail->edit($this->request->post())) {
            return $this->renderMsg('更新成功');
        }
        $error = $detail->getError() ?: '更新失败';
		return $this->renderError($error);
    }

    /**
     * 设为默认地址
     */
    public function setDefault($id) {
        $model = AddressModel::get($id);
        if ($model->setDefault($this->user)) {
            return $this->renderMsg('设置成功');
        }
        $error = $model->getError() ?: '设置失败';
		return $this->renderError($error);
    }

    /**
     * 删除收货地址
     */
    public function delete($id)
    {
        $model = AddressModel::get($id);
        if ($model->remove($this->user)) {
            return $this->renderMsg('删除成功');
        }
        $error = $model->getError() ?: '删除失败';
		return $this->renderError($error);
    }
	
	
	/**
     * 获取用户位置
     */
    public function getLocation(string $location)
    {
        $map = new Map;
		if ($location = $map->getLocation($location)){
            return $this->renderSuccess(compact('location'));
        }
		return $this->renderError($map->getError());
    }

}
